<?php

namespace App\Repositories;

use App\Models\OperationLog;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Arr;

class OperationLogRepository extends BaseRepository
{
    public function __construct(OperationLog $model)
    {
        parent::__construct($model);
    }

    public function pagination(array $params): LengthAwarePaginator
    {
        $query = $this->query();
        $keyword = Arr::get($params, 'keyword', '');
        if ($keyword) {
            $query->where(function ($query) use ($keyword) {
                $query->where('name', 'like', "%{$keyword}%")
                    ->orWhere('ip', 'like', "%{$keyword}%")
                    ->orWhere('url', 'like', "%{$keyword}%");
            });
        }
        $keyword = Arr::get($params, 'method', '');
        if ($keyword) {
            $query->where('method', $keyword);
        }

        $startDate = Arr::get($params, 'startDate', '');
        $endDate = Arr::get($params, 'endDate', '');
        if ($startDate && $endDate) {
            $query->whereBetween('created_at', [$startDate . ' 00:00:00', $endDate . ' 23:59:59']);
        }

        return $query->orderBy('id', 'desc')->paginate(10)->through(fn(OperationLog $row) => [
            'id' => $row->id,
            'name' => $row->name,
            'ip' => $row->ip,
            'method' => $row->method,
            'url' => $row->url,
            'params' => $row->params,
            'status_code' => $row->status_code,
            'duration' => $row->duration,
            'created_at' => $row->created_at->format('Y-m-d H:i:s'),
        ]);
    }
}
